<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="模型名称" prop="modelName">
        <el-input
          v-model="queryParams.modelName"
          placeholder="请输入模型名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="省" prop="province">
        <el-select v-model="queryParams.province" placeholder="请选择省" @change="chooseProvince" clearable>
           <el-option
                v-for="item in provinceData"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="市" prop="city">
        <el-select v-model="queryParams.city" placeholder="请选择市" @change="chooseCity" clearable>
           <el-option
                v-for="item in cityData"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
        </el-select>
      </el-form-item>
      
      
      
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="casualtiesList">
      <!--<el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="单选" width="55px">
        <template #default="scope">
          <el-radio :label="scope.row.id" v-model="selectRadio"
                    @click.native.stop.prevent="getCurrentRow(scope.row)">&nbsp;</el-radio>
        </template>
      </el-table-column>
      <el-table-column label="模型名称" align="center" prop="modelName" >
      	<template #default="scope">
            <el-button type="text" @click="edit(scope.row)">{{
              scope.row.modelName
            }}</el-button>
      	</template>
    	</el-table-column>
      <el-table-column label="省" align="center" prop="province" />
      <el-table-column label="市" align="center" prop="city" />
      
      
      <el-table-column label="是否默认" align="center" prop="isDefault">
      	<template #default="scope">
          <span v-if="scope.row.isDefault=='0'">否</span>
          <span v-if="scope.row.isDefault=='1'">是</span>
        </template>
      </el-table-column>
      <el-table-column label="维护人" align="center" prop="createUserName" />
      <el-table-column label="维护人所属单位" align="center" prop="orgName" />
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.rows"
      @pagination="getList"
    />

    <!--确定选择模型-->
    <p style="text-align: center;margin-top:30px;">
      <el-button type="primary" @click="submitModelSelect">确定</el-button>
    </p>

    <!-- 添加或修改区县致死性差异性对话框 -->
    <el-dialog :title="title" v-model="open" width="850px" append-to-body>
      <el-form ref="casualtiesRef" :model="form" :rules="rules" label-width="120px">
      	<p class="dialogTitle">{{title}}</p>
 				<el-row>
   				<el-col :span="12">
	       		<el-form-item label="模型名称" prop="modelName" v-if="isCopy">
	       			{{form.modelName}}		          
		        </el-form-item>
		        <el-form-item label="模型名称" prop="modelName" v-else>
	       			<el-input v-model="form.modelName" placeholder="请输入模型名称" />		          
		        </el-form-item>
	       	</el-col>
	       	<el-col :span="12">
	       		<el-form-item label="是否默认" prop="" v-if="isCopy">
	       			{{form.isDefault=='0'?'否':'是'}}		          
		        </el-form-item>
		        <el-form-item label="是否默认" prop="" v-else>
	       			<el-select v-model="form.isDefault" disabled style="width: 100%;">
	               <el-option
	                v-for="item in [
	                  { value: '0', label: '否' },
	                  { value: '1', label: '是' },
	                ]"
	                :key="item.value"
	                :label="item.label"
	                :value="item.value"
	              >
              	</el-option>
	           	</el-select>	          
		        </el-form-item>
	       	</el-col>
	       	
   			</el-row>
 				<el-row>
	  			<el-col :span="24">
		        <el-form-item label="地区" prop="" v-if="isCopy||isEditDefault">
		          {{form.province}} - {{form.city}}
		        </el-form-item>
		        <el-form-item label="地区" prop="" v-else>		          
		          <el-form-item label="省" prop="provinceId" label-width="50px">
			          <el-select v-model="form.provinceId" placeholder="请输入省" @change="chooseFormProvince"  style="width: 160px;">
		           		<el-option
		                v-for="item in provinceFormData"
		                :key="item.id"
		                :label="item.name"
		                :value="item.id">
		            	</el-option>
		        		</el-select>
	        		</el-form-item>
	        		<el-col :span="16">
	        			<el-form-item label="市" prop="" label-width="50px">
	        				<el-radio-group v-model="radio" @change="chooseRadio">
							      <el-radio label="1">全部</el-radio>
							      <el-radio label="2">
							      	<el-select v-model="form.cityId" placeholder="请输入市" multiple collapse-tags :disabled="isCityEdit" style="width: 200px;">
					           		<el-option
					                v-for="item in cityFormData"
					                :key="item.id"
					                :label="item.name"
					                :value="item.id">
					            	</el-option>
					        		</el-select>
							      </el-radio>
							    </el-radio-group>
		  					</el-form-item>
  						</el-col>
		        </el-form-item>
		    	</el-col>
	       
       	</el-row>
   			<el-row>
   				<el-col :span="12">
	       		<el-form-item label="维护人" prop="">
	       			{{form.createUserName}}		          
		        </el-form-item>
	       	</el-col>
	       	<el-col :span="12">
	       		<el-form-item label="维护人单位" prop="">
	       			{{form.orgName}}		          
		        </el-form-item>
	       	</el-col>
	       	
   			</el-row>
   			
 				<div>
        <el-row>
					<el-col :span="6" class="tab-title">
						椭圆衰减模型
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12" :offset="6" v-if="isCopy">
						<span style="font-size: 16px;font-weight: bold;font-style: italic;">长轴： I<sub>a</sub> = 4.9024 + 1.3485M - 3.9738 lg(R<sub>a</sub> + 13) </span><br/><br/>
						<span style="font-size: 16px;font-weight: bold;font-style: italic;">短轴： I<sub>b</sub> = 4.3517 + 1.2192M - 3.7429 lg(R<sub>b</sub> + 6) </span><br/><br/>
						I<sub>a</sub>、I<sub>b</sub>分别为长短轴烈度，M为震级，R<sub>a</sub>、R<sub>b</sub>分别为烈度为 I 时长、短半轴的长度。<br/>
						
					</el-col>
					<el-col :span="22" :offset="2" v-else>
						<span style="font-size: 16px;font-weight: bold;font-style: italic;">长轴： I<sub>a</sub> = 
							<el-form-item prop="longRatio1" label-width="0" style="display: inline-block;">
								<el-input v-model="form.longRatio1" placeholder="保留四位小数" style="width: 120px;" />
							</el-form-item>
							 + 
							 <el-form-item prop="longRatio2" label-width="0" style="display: inline-block;">
							 	<el-input v-model="form.longRatio2" placeholder="保留四位小数" style="width: 120px;" />
							 </el-form-item>
							 	M - 
							 	<el-form-item prop="longRatio3" label-width="0" style="display: inline-block;">
							 		<el-input v-model="form.longRatio3" placeholder="保留四位小数" style="width: 120px;" /> 
							 	</el-form-item>
							<el-select v-model="form.longSymbol"  style="width: 60px;">
	               <el-option
	                v-for="item in [
	                  { value: 'lg', label: 'lg' },
	                  { value: 'In', label: 'In' },
	                ]"
	                :key="item.value"
	                :label="item.label"
	                :value="item.value"
	              >
              	</el-option>
	           	</el-select>
	           	(R<sub>a</sub> + 
	           	<el-form-item prop="longRatio4" label-width="0" style="display: inline-block;">
	           		<el-input v-model="form.longRatio4" placeholder="自然数" style="width: 100px;" />
           		</el-form-item>) </span><br/><br/>
						<span style="font-size: 16px;font-weight: bold;font-style: italic;">短轴： I<sub>b</sub> = 
							<el-form-item prop="shortRatio1" label-width="0" style="display: inline-block;">
								<el-input v-model="form.shortRatio1" placeholder="保留四位小数" style="width: 120px;" />
							</el-form-item>
							 + 
						 	<el-form-item prop="shortRatio2" label-width="0" style="display: inline-block;">
							 	<el-input v-model="form.shortRatio2" placeholder="保留四位小数" style="width: 120px;" />
							</el-form-item> 
							 M - 
							<el-form-item prop="shortRatio3" label-width="0" style="display: inline-block;">
							 	<el-input v-model="form.shortRatio3" placeholder="保留四位小数" style="width: 120px;" /> 
							</el-form-item> 
							<el-select v-model="form.shortSymbol"  style="width: 60px;">
	               <el-option
	                v-for="item in [
	                  { value: 'lg', label: 'lg' },
	                  { value: 'In', label: 'In' },
	                ]"
	                :key="item.value"
	                :label="item.label"
	                :value="item.value"
	              >
              	</el-option>
	           	</el-select> (R<sub>b</sub> + 
	           	<el-form-item prop="shortRatio4" label-width="0" style="display: inline-block;">
	           		<el-input v-model="form.shortRatio4" placeholder="自然数" style="width: 100px;" />
	           	</el-form-item>) </span><br/><br/>
						I<sub>a</sub>、I<sub>b</sub>分别为长短轴烈度，M为震级，R<sub>a</sub>、R<sub>b</sub>分别为烈度为 I 时长、短半轴的长度。<br/>
						
					</el-col>
				</el-row>
				</div>
				
        <div v-if="type=='1'">
        <el-row style="margin-top: 30px;">
					<el-col :span="6" class="tab-title">
						破裂尺度公式
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12" :offset="6" v-if="isCopy">
						<span style="font-size: 16px;font-weight: bold;font-style: italic;">M = 5.08 + 1.16 * log(SRL) </span><br/><br/>
						SRL为地表破裂带长度<br/>
						最终的长轴长度=R<sub>a</sub> * 2 + SRL<br/>
						长短轴比例：1.97<br/>
						
					</el-col>
					<el-col :span="12" :offset="6" v-else>
						<span style="font-size: 16px;font-weight: bold;font-style: italic;">
							M = 
							<el-form-item prop="formulaRatio1" label-width="0" style="display: inline-block;">
								<el-input v-model="form.formulaRatio1" placeholder="保留二位小数" style="width: 120px;" />
							</el-form-item>
							 + 
							 <el-form-item prop="formulaRatio2" label-width="0" style="display: inline-block;">
							 	<el-input v-model="form.formulaRatio2" placeholder="保留二位小数" style="width: 120px;" />
							 </el-form-item>	
							 	* log(SRL)</span><br/><br/>
						SRL为地表破裂带长度<br/>
						最终的长轴长度=R<sub>a</sub> * 2 + SRL<br/>
						长短轴比例：<el-form-item prop="scale" label-width="0" style="display: inline-block;">
	       			<el-input v-model="form.scale" placeholder="保留二位小数" style="width: 120px;" />		          
		        </el-form-item><br/>
						
					</el-col>
				</el-row>
				</div>
        
        
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listIntensity, getModelIntensity } from "@/api/fastDisasterAnalysis/fastSeismicInfluence/intensity";
import { getProvince, getProvince2, getChildArea} from "@/api/system/division";

const { proxy } = getCurrentInstance();
const emit = defineEmits(['sureSelectModel']);

const casualtiesList = ref([]);
const isEdit = ref(false);
const isCopy = ref(true);
const Default = ref("1");
const radio = ref("1");
const isCityEdit = ref(true);
const isEditDefault = ref(true);
const isShow = ref(true);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const submitTime = ref("");//提交时间
const provinceData = ref([]);//省
const cityData = ref([]);//市
const areaData = ref([]);//区、县

const provinceFormData = ref([]);//表单省 
const cityFormData = ref([]);//表单市
const areaFormData = ref([]);//表单区、县
const type = ref("");

// 保留两位小数
const positive2decimals = (rule, value, callback) => {
	value = String(value)
	if (isNaN(value)|| !value) {
    return callback(new Error());
  }
  var re = /^([0-9]+[\d]*(.[0-9]{2}))$/;
  if (!re.test(value)) {
    callback(new Error());
  }else{
    callback();
  }
}
// 保留四位小数
const positive4decimals = (rule, value, callback) => {
	value = String(value)
	if (isNaN(value)|| !value) {
    return callback(new Error());
  }
  var re = /^([0-9]+[\d]*(.[0-9]{4}))$/;
  if (!re.test(value)) {
    callback(new Error());
  }else{
    callback();
  }
}

// 自然数校验
const positiveInteger = (rule, value, callback) => {
	value = String(value)
  if (isNaN(value)|| !value) {
    return callback(new Error());
  }
  var re = /^([1-9][0-9]*|0)$/;
  if (!re.test(value)) {
    callback(new Error());
  }else{
    callback();
  }
}
const data = reactive({
  form: {},
  queryParams: {
    page: 1,
    rows: 10,
    province: null,
    city: null,
    
  },
  rules: {
    taskCode: [
      { required: true, message: "任务编号不能为空", trigger: "blur" }
    ],
    modelName: [
      { required: true, message: "模型名称不能为空", trigger: "blur" }
    ],
    province: [
      { required: true, message: "省不能为空", trigger: "blur" }
    ],
    provinceId: [
      { required: true, message: "省不能为空", trigger: "change" }
    ],
    city: [
      { required: true, message: "市不能为空", trigger: "blur" }
    ],
    cityId: [
      { required: true, message: "市不能为空", trigger: "blur" }
    ],
    area: [
      { required: true, message: "区/县不能为空", trigger: "blur" }
    ],
    areaId: [
      { required: true, message: "区/县 不能为空", trigger: "blur" }
    ],
    longRatio1: [
      { required: true, message: "保留四位小数", trigger: "blur", validator: positive4decimals }
    ],
    longRatio2: [
      { required: true, message: "保留四位小数", trigger: "blur", validator: positive4decimals }
    ],
    longRatio3: [
      { required: true, message: "保留四位小数", trigger: "blur", validator: positive4decimals }
    ],
    longRatio4: [
      { required: true, message: "输入自然数", trigger: "blur", validator: positiveInteger }
    ],
    shortRatio1: [
      { required: true, message: "保留四位小数", trigger: "blur", validator: positive4decimals }
    ],
    shortRatio2: [
      { required: true, message: "保留四位小数", trigger: "blur", validator: positive4decimals }
    ],
    shortRatio3: [
      { required: true, message: "保留四位小数", trigger: "blur", validator: positive4decimals }
    ],
    shortRatio4: [
      { required: true, message: "输入自然数", trigger: "blur", validator: positiveInteger }
    ],
    formulaRatio1: [
      { required: true, message: "保留两位小数", trigger: "blur", validator: positive2decimals }
    ],
    formulaRatio2: [
      { required: true, message: "保留两位小数", trigger: "blur", validator: positive2decimals }
    ],
    scale: [
      { required: true, message: "保留两位小数", trigger: "blur", validator: positive2decimals }
    ],

  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询人口伤亡计算模型列表 */
function getList() {
  loading.value = true;
  listIntensity(queryParams.value).then(response => {
    casualtiesList.value = response.data.rows;;
    total.value = response.data.total;
    loading.value = false;
  });
}

/** 获取省列表 */
function getProvinceData() {
	getProvince2().then(response => {
	    provinceData.value = response.data;
	});
}

function getProvinceFormData() {
	getProvince().then(response => {
	    provinceFormData.value = response.data;
	});
}

function editProvinceFormData(provinceId,cityId) {
	getProvince().then(response => {
	    provinceFormData.value = response.data;
	});
	getChildArea(provinceId).then(response => {
    cityFormData.value = response.data;
	});
	getChildArea(cityId).then(response => {
	    areaFormData.value = response.data;
	});
}

function chooseRadio(value){
	console.log(value)
	if(value == "2"){
		isCityEdit.value = false
		
	}else{
		isCityEdit.value = true
		form.value.city = "全部"
		form.value.cityId = ""
	}
}

function chooseProvince(value){
	queryParams.value.city = null;
	queryParams.value.area = null;
	cityData.value = [];
	areaData.value = [];
	getChildArea(value).then(response => {
    cityData.value = response.data;
	});
//	provinceData.value.map(item => {//遍历数据
//		if(item.id == value){
//			if(item.name == "北京市"||item.name == "天津市"||item.name == "上海市"||item.name == "重庆市"){
//		    cityData.value.push(JSON.parse(JSON.stringify(item)));
//			}else{
//				getChildArea(value).then(response => {
//			    cityData.value = response.data;
//				});
//			}
//			return;
//		}   
//})		
}

function chooseFormProvince(value){
	form.value.city = null;
	form.value.area = null;
	cityFormData.value = [];
	areaFormData.value = [];
	getChildArea(value).then(response => {
    cityFormData.value = response.data;
	});	
}

function chooseCity(value){
	queryParams.value.areaId = null;
	areaData.value = [];
	getChildArea(value).then(response => {
	    areaData.value = response.data;
	});
}

function chooseFormCity(value){
	form.value.area = null;
	areaFormData.value = [];
	getChildArea(value).then(response => {
	    areaFormData.value = response.data;
	});
}
function chooseTaskName(value){
	taskNameData.value.map(item => {//遍历数据
		if(item.taskName == value){
			form.value.taskCode = item.taskNum;
			console.log(form.value.taskCode)
			return;
		}   
	})	

}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    modelName: null,
    province: null,
    provinceId: null,
    city: null,
    cityId: null,
    area: null,
    areaId: null,

    smrsNumber1: null,
    smrsNumber2: null,
    injuries: null,
    isDefault: null,
    deathNumber: null,

  };
  proxy.resetForm("casualtiesRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.page = 1;
  
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
	cityData.value = [];
	areaData.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

//获取当前日期函数
function getNowFormatDate() {
  let date = new Date(),
    seperator1 = '-', //格式分隔符
    year = date.getFullYear(), //获取完整的年份(4位)
    month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
    strDate = date.getDate() // 获取当前日(1-31)
  if (month >= 1 && month <= 9) month = '0' + month // 如果月份是个位数，在前面补0
  if (strDate >= 0 && strDate <= 9) strDate = '0' + strDate // 如果日是个位数，在前面补0
 
  let currentdate = year + seperator1 + month + seperator1 + strDate 
  return currentdate
}



/** 查看按钮操作 */
function edit(row) {
  reset();
  type.value = "";
  const id = row.id 
  if(row.isDefault=="1"){
  	isCopy.value = true;
  	Default.value = "1";
  	title.value = "系统默认地震烈度衰减模型";
  }else{
  	// isCopy.value = false;
    isCopy.value = true;//不编辑
  	Default.value = "0";
  	title.value = "地震烈度衰减模型";
  }
  if(row.type == "0"){
  	type.value = "0"
  }
  if(row.type == "1"){
  	type.value = "1"
  }
  
  getModelIntensity(id).then(response => {
  	
    form.value = response.data;
    
    open.value = true;
    if(form.value.city=="全部"){
    	radio.value = "1"
    	isCityEdit.value = true
    }else{
    	radio.value = "2"
    	isCityEdit.value = false
    }
    if(form.value.isDefault=="0"){
    	isEditDefault.value = true
    }else{
    	isEditDefault.value = false
    }
    
  });
}

//选择模型
const selectionData = ref({});
const selectRadio = ref('');

//单选选择
function getCurrentRow(row) {
  if (selectRadio.value) {
    if (selectRadio.value == row.id) {
      selectRadio.value = ''
      selectionData.value = {};// 取消勾选就把回传数据清除
      return;
    }
  }
  selectRadio.value = row.id;
  selectionData.value = row;
}

//确定选择模型
const submitModelSelect = ()=>{
  if (selectRadio.value) {
    emit("sureSelectModel",selectionData.value);
  }else{
    proxy.$modal.msgWarning("请选取模型");
  }
}



getList();
getProvinceData();
getProvinceFormData();
</script>
<style scoped lang="scss">
	.tab-title {
		font-size: 16px;
		font-weight: bold;
		border-left: 4px solid #0D9AFF;
		font-family: PingFangSC-Medium;
		padding-left: 10px;
		margin-bottom: 20px;
	}
</style>
